<template>
  <div class="category">
    <div class="header-box" style="position: relative">
      <h2>菜单分配</h2>
      <el-button
          :disabled="!showButton"
          :icon="Check"
          style="position: absolute; right: 10px"
          type="primary"
          @click="saveMenu"
      >保存
      </el-button
      >
    </div>
    <div class="list system-scrollbar">
      <el-tree
          ref="menu"
          class="my-tree"
          :data="data"
          show-checkbox
          :props="defaultProps"
          v-if="lodding"
          :default-checked-keys="activeData"
          :default-expanded-keys="activeData"
          :expand-on-click-node="true"
          node-key="menuId"
          :highlight-current="false"
      >
      </el-tree>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {Ref, watch} from "vue";
import {ref, inject} from "vue";
import {Check} from "@element-plus/icons";
import {getData, getMenuByRoleId} from "@/api/system/menu";
import {roleIdSaveMenus} from "@/api/system/role";
import {cpSync} from "fs";
import {ElMessage} from "element-plus";

let data = ref([]);
let menu = ref();
let showButton = ref(false);
let lodding = ref(true);
let activeData = ref([]);
const tree: Ref<any | null> = ref(null);
const defaultProps = {
  children: "children",
  label: "name",
  id: "menuId",
};
const active: any = inject("active");
const getTreeData = () => {
  let params = {};
  getData(params).then((res) => {
    data.value = res.data;
  });
};
// 获取当前角色的所有菜单
const getActiveData = () => {
  let roleId = active.value;
  lodding.value = false;
  getMenuByRoleId(roleId).then((res) => {
    showButton.value = true;
    activeData.value = res.data;
    lodding.value = true;
  });
};

// 触发单选
watch(active, (newVal) => {
  getActiveData();
});

const saveMenu = () => {
  let menuKeys = menu.value.getCheckedKeys();
  let activeId = active.value;
  //保存当前角色的菜单授权
  roleIdSaveMenus(activeId, menuKeys).then((res) => {
    ElMessage({
      type: "success",
      message: "授权成功",
    });
  });
};
getTreeData();
</script>

<style lang="scss" scoped>
.category {
  background: #fff;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .header-box {
    padding: 10px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #eee;

    h2 {
      padding: 0;
      margin: 0;
      margin-right: 20px;
      font-size: 14px;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      overflow: hidden;
      height: 30px;
      line-height: 30px;
    }

    .el-input {
      flex: 1;
    }
  }

  .list {
    flex: 1;
    overflow: auto;
  }

  .my-tree {
    :deep(.el-tree-node__content) {
      height: 35px;
    }

    :deep(.el-tree-node.is-current > .el-tree-node__content) {
      background-color: rgba(64, 158, 255, 0.4);
    }

    :deep(.el-tree-node > .el-tree-node__content) {
      transition: 0.2s;
    }
  }
}
</style>